<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.name" placeholder="登录名或姓名搜索" style="width: 200px;" class="filter-item" clearable />
      <el-input v-model="listQuery.appName" placeholder="app名称搜索" style="width: 200px;" class="filter-item" clearable />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查找
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新建用户
      </el-button>
    </div>
    <el-table :data="list" border fit highlight-current-row style="width: 100%">
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="primary" size="mini" @click="resetPassword(row)">
            重设密码
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="ID" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="姓名">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="用户名">
        <template slot-scope="scope">
          <span>{{ scope.row.username }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="描述">
        <template slot-scope="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="关联租户">
        <template slot-scope="scope">
          <span>{{ scope.row.tenantList| filterTenantListName }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="角色列表">
        <template slot-scope="scope">
          <span>{{ scope.row.roleList| filterRoleListName }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="所属app">
        <template slot-scope="scope">
          <span>{{ scope.row.appList| filterAppListName }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNumber"
      :limit.sync="listQuery.pageSize"
      @pagination="getList"
    />

    <CreateAppUser
      ref="CreateAppUserForm"
      :text-map="textMap"
      :dialog-status="dialogStatus"
      :dialog-form-visible.sync="dialogFormVisible"
      @on-fresh-list="getList"
    />

  </div>
</template>

<script>
import * as apiAppUser from '@/api/app_user'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
// 当然你也可以为了方便使用，将它注册到全局
import permission from '@/directive/permission/index.js' // 权限判断指令
import CreateAppUser from '@/views/app_user/createAppUser'
import { MessageBox } from 'element-ui'

export default {
  name: 'AppUser',
  components: { Pagination, CreateAppUser },
  directives: { waves, permission },
  filters: {
    filterTenantListName(tenantList) {
      if (tenantList.length == 0) {
        return '无'
      }
      let tenantNameList = []
      tenantList.forEach((tenant)=>{
        tenantNameList.push(tenant.name)
      })
      return tenantNameList.join(',')
    },
    filterRoleListName(roleList) {
      if (roleList.length == 0) {
        return '无'
      }
      let roleNameList = []
      roleList.forEach((role)=>{
        roleNameList.push(role.roleName)
      })
      return roleNameList.join(',')
    },
    filterAppListName(appList) {
      if (appList.length == 0) {
        return '无'
      }
      let appNameList = []
      appList.forEach((app)=>{
        appNameList.push(app.fullname)
      })
      return appNameList.join(',')
    }
  },
  data() {
    return {
      list: null,
      total: 0,
      listQuery: { // 查询列表时的参数对象
        pageNumber: 1,
        pageSize: 50,
        name: undefined,
        appName: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      }
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    // 测试用
    // var that = this
    // setTimeout(function() {
    //   that.dialogFormVisible = true
    // }, 5000)
  },
  beforeDestroy() { // 当路由切换到其他页面时触发
    // alert('离开用户管理界面')
  },
  methods: {
    async getList() { // 获取列表数据
      const { content } = await apiAppUser.getList(this.listQuery)
      this.list = content.list
      this.total = content.totalCounts
    },
    handleFilter() {
      this.listQuery.pageNumber = 1
      this.getList()
    },
    handleCreate() {
      this.$refs['CreateAppUserForm'].clearFormData() // 直接调用子组件的method, 很方便
      this.$refs['CreateAppUserForm'].initWhenCreate()
      this.$refs['CreateAppUserForm'].getTenantList()
      this.$refs['CreateAppUserForm'].getRoleList()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['CreateAppUserForm'].$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate(row) {
      console.log('row--->', row)
      const currentRow = Object.assign({}, row)
      this.$refs['CreateAppUserForm'].setCurrentRow(currentRow)
      this.$refs['CreateAppUserForm'].getTenantList()
      this.$refs['CreateAppUserForm'].getRoleList()
      this.$refs['CreateAppUserForm'].clearPassword()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['CreateAppUserForm'].$refs['dataForm'].clearValidate()
      })
    },
    resetPassword(row) {
      console.log('row--->', row)

      this.$prompt('请输入新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(({ value }) => {
        if(value.length < 6) {
          alert('密码长度至少为6')
          return
        }
        const apiData = {userId: row.id, newPassword: value}
        apiAppUser.resetPassword(apiData).then((res)=>{
          this.$message({
            type: 'info',
            message: res.message
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
    handleDelete(row) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const deleteData = Object.assign({}, row) // copy obj
        apiAppUser.deleteAppUser(deleteData.id).then(() => {
          // 刷新列表数据
          this.getList()
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style scoped>
  .app-select {
    margin-bottom: 20px;
  }

</style>
